{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2022年2月2日是这一年的第33天。\n"
     ]
    }
   ],
   "source": [
    "def is_leap_year(year):\n",
    "    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):\n",
    "        return True\n",
    "    else:\n",
    "        return False\n",
    " \n",
    "def day_of_year(year, month, day):\n",
    "    # 每个月的天数（平年）\n",
    "    days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n",
    "    \n",
    "    # 如果是闰年，则2月有29天\n",
    "    if is_leap_year(year):\n",
    "        days_in_month[1] = 29\n",
    "    \n",
    "    # 累加前几个月的天数\n",
    "    day_count = sum(days_in_month[:month - 1])\n",
    "    \n",
    "    # 加上当前月的天数\n",
    "    day_count += day\n",
    "    \n",
    "    return day_count\n",
    " \n",
    "# 示例输入\n",
    "year = int(input(\"请输入年份: \"))\n",
    "month = int(input(\"请输入月份: \"))\n",
    "day = int(input(\"请输入日期: \"))\n",
    " \n",
    "# 计算并输出结果\n",
    "print(f\"{year}年{month}月{day}日是这一年的第{day_of_year(year, month, day)}天。\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1000以内有168个素数。\n",
      "1000以内的素数有：\n",
      "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 "
     ]
    }
   ],
   "source": [
    "def sieve_of_eratosthenes(limit):\n",
    "    # 初始化一个布尔列表，假设所有数（从0到limit）都标记为素数（True）\n",
    "    is_prime = [True] * (limit + 1)\n",
    "    # 0和1不是素数，因此将它们标记为非素数（False）\n",
    "    is_prime[0], is_prime[1] = False, False\n",
    "    \n",
    "    # 使用埃拉托斯特尼筛法来筛选素数\n",
    "    for p in range(2, int(limit**0.5) + 1):\n",
    "        if is_prime[p]:  # 如果p是素数\n",
    "            # 将p的所有倍数（从p的平方开始，直到limit）标记为非素数\n",
    "            for multiple in range(p*p, limit + 1, p):\n",
    "                is_prime[multiple] = False\n",
    "    \n",
    "    # 收集所有被标记为素数的数字\n",
    "    primes = [p for p in range(2, limit + 1) if is_prime[p]]\n",
    "    return primes\n",
    " \n",
    "# 设定搜索范围的上限\n",
    "limit = 1000\n",
    "# 调用函数获取1000以内的所有素数\n",
    "primes = sieve_of_eratosthenes(limit)\n",
    "# 输出素数的数量\n",
    "print(f\"1000以内有{len(primes)}个素数。\")\n",
    "# 输出所有素数\n",
    "print(\"1000以内的素数有：\")\n",
    "for prime in primes:\n",
    "    print(prime, end=' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "学习成绩 82.0 分对应的等级是: B\n"
     ]
    }
   ],
   "source": [
    "# 获取用户输入的学习成绩\n",
    "score = float(input(\"请输入学习成绩(0-100): \"))\n",
    " \n",
    "# 使用嵌套的条件运算符来判断等级\n",
    "grade = 'A' if score >= 90 else ('B' if 60 <= score < 90 else 'C')\n",
    " \n",
    "# 输出结果\n",
    "print(f\"学习成绩 {score} 分对应的等级是: {grade}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "英文字母个数: 0\n",
      "空格个数: 0\n",
      "数字个数: 6\n",
      "其他字符个数: 0\n"
     ]
    }
   ],
   "source": [
    "# 获取用户输入的字符串\n",
    "input_string = input(\"请输入一行字符串: \")\n",
    " \n",
    "# 初始化计数器\n",
    "letters_count = 0\n",
    "spaces_count = 0\n",
    "digits_count = 0\n",
    "others_count = 0\n",
    " \n",
    "# 遍历字符串中的每个字符\n",
    "for char in input_string:\n",
    "    if char.isalpha():  # 判断是否是英文字母\n",
    "        letters_count += 1\n",
    "    elif char.isspace():  # 判断是否是空格\n",
    "        spaces_count += 1\n",
    "    elif char.isdigit():  # 判断是否是数字\n",
    "        digits_count += 1\n",
    "    else:  # 其他字符\n",
    "        others_count += 1\n",
    " \n",
    "# 输出统计结果\n",
    "print(f\"英文字母个数: {letters_count}\")\n",
    "print(f\"空格个数: {spaces_count}\")\n",
    "print(f\"数字个数: {digits_count}\")\n",
    "print(f\"其他字符个数: {others_count}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1000以内的所有完数有:\n",
      "[6, 28, 496]\n"
     ]
    }
   ],
   "source": [
    "def find_factors(n):\n",
    "    \"\"\"找出n的所有因子(不包括n本身)\"\"\"\n",
    "    factors = []\n",
    "    for i in range(1, n):\n",
    "        if n % i == 0:\n",
    "            factors.append(i)\n",
    "    return factors\n",
    " \n",
    "def is_perfect_number(n):\n",
    "    \"\"\"判断n是否为完数\"\"\"\n",
    "    factors = find_factors(n)\n",
    "    return sum(factors) == n\n",
    " \n",
    "# 找出1000以内的所有完数\n",
    "perfect_numbers = []\n",
    "for num in range(1, 1001):\n",
    "    if is_perfect_number(num):\n",
    "        perfect_numbers.append(num)\n",
    " \n",
    "# 输出结果\n",
    "print(\"1000以内的所有完数有:\")\n",
    "print(perfect_numbers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 + 2! + 3! + ... + 55! 的值是: 12931604174610554792808543145134839786142796265765134511963408920420940313\n"
     ]
    }
   ],
   "source": [
    "def factorial(n):\n",
    "    \"\"\"计算n的阶乘\"\"\"\n",
    "    if n == 0 or n == 1:\n",
    "        return 1\n",
    "    else:\n",
    "        return n * factorial(n - 1)\n",
    " \n",
    "def sum_of_factorials(N):\n",
    "    \"\"\"计算1 + 2! + 3! + ... + N!的值\"\"\"\n",
    "    total = 0\n",
    "    for i in range(1, N + 1):\n",
    "        total += factorial(i)\n",
    "    return total\n",
    " \n",
    "# 获取用户输入的N\n",
    "N = int(input(\"请输入一个整数N: \"))\n",
    " \n",
    "# 计算并输出结果\n",
    "result = sum_of_factorials(N)\n",
    "print(f\"1 + 2! + 3! + ... + {N}! 的值是: {result}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入的不是奇数，请重新输入。\n",
      "           *\n",
      "          ***\n",
      "          *****\n",
      "         *******\n",
      "         *********\n",
      "        ***********\n",
      "        *************\n",
      "       ***************\n",
      "       *****************\n",
      "      *******************\n",
      "      *********************\n",
      "     ***********************\n",
      "     *********************\n",
      "      *******************\n",
      "      *****************\n",
      "       ***************\n",
      "       *************\n",
      "        ***********\n",
      "        *********\n",
      "         *******\n",
      "         *****\n",
      "          ***\n",
      "          *\n"
     ]
    }
   ],
   "source": [
    "def print_diamond(N):\n",
    "    # 确保N是奇数\n",
    "    if N % 2 == 0:\n",
    "        print(\"请输入一个奇数N。\")\n",
    "        return\n",
    "    \n",
    "    # 上半部分（包括中间行）\n",
    "    for i in range(1, (N + 1) // 2 + 1):\n",
    "        # 计算每行前面的空格数\n",
    "        spaces = ' ' * ((N - i) // 2)\n",
    "        # 计算每行的星号数\n",
    "        stars = '*' * (2 * i - 1)\n",
    "        # 打印一行\n",
    "        print(spaces + stars)\n",
    "    \n",
    "    # 下半部分（不包括中间行）\n",
    "    for i in range((N - 1) // 2, 0, -1):\n",
    "        # 计算每行前面的空格数\n",
    "        spaces = ' ' * ((N - i - 1) // 2)\n",
    "        # 计算每行的星号数（与上半部分对应行相同）\n",
    "        stars = '*' * (2 * i - 1)\n",
    "        # 打印一行\n",
    "        print(spaces + stars)\n",
    " \n",
    "# 获取用户输入的奇数N\n",
    "while True:\n",
    "    try:\n",
    "        N = int(input(\"请输入一个奇数N: \"))\n",
    "        if N % 2 != 0:\n",
    "            break\n",
    "        else:\n",
    "            print(\"输入的不是奇数，请重新输入。\")\n",
    "    except ValueError:\n",
    "        print(\"输入无效，请输入一个整数。\")\n",
    " \n",
    "# 打印菱形图案\n",
    "print_diamond(N)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原始列表: [9, 10, 28, 24, 6, 79, 65, 93, 67, 15]\n",
      "排序后的列表: [6, 9, 10, 15, 24, 28, 65, 67, 79, 93]\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    " \n",
    "# 生成一个包含10个随机数的列表\n",
    "numbers = [random.randint(1, 100) for _ in range(10)]\n",
    " \n",
    "# 打印原始列表\n",
    "print(\"原始列表:\", numbers)\n",
    " \n",
    "# 使用Python内置的sorted()函数或列表的sort()方法对列表进行排序\n",
    "# sorted()函数返回一个新的排序后的列表，而sort()方法是在原地对列表进行排序\n",
    "sorted_numbers = sorted(numbers)  # 使用sorted()函数\n",
    "# numbers.sort()  # 或者使用sort()方法，如果你不需要保留原始列表\n",
    " \n",
    "# 打印排序后的列表\n",
    "print(\"排序后的列表:\", sorted_numbers)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "插入后的数组: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 55]\n"
     ]
    }
   ],
   "source": [
    "# 假设我们有一个已经排好序的数组\n",
    "sorted_array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]\n",
    " \n",
    "# 从键盘读取用户输入的数\n",
    "user_input = int(input(\"请输入一个要插入的数: \"))\n",
    " \n",
    "# 找到应该插入新数的位置\n",
    "# 使用列表推导式和next()函数与默认参数来找到第一个大于或等于user_input的元素的索引\n",
    "# 如果所有元素都小于user_input，则插入到列表末尾（即len(sorted_array)的位置）\n",
    "insert_index = next((i for i, x in enumerate(sorted_array) if x >= user_input), len(sorted_array))\n",
    " \n",
    "# 在找到的位置插入新数\n",
    "sorted_array.insert(insert_index, user_input)\n",
    " \n",
    "# 打印排序后的数组（实际上，由于我们是在已排序数组中插入，所以它仍然是排序的）\n",
    "print(\"插入后的数组:\", sorted_array)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最后留下的是原来第67号的那位。\n"
     ]
    }
   ],
   "source": [
    "def josephus(n, k):\n",
    "    \"\"\"\n",
    "    解决约瑟夫环问题\n",
    "    :param n: 总人数\n",
    "    :param k: 报数的间隔（每次报到k的人退出）\n",
    "    :return: 最后留下的人的编号\n",
    "    \"\"\"\n",
    "    # 初始化一个列表来表示圈子中的人，编号从1到n\n",
    "    people = list(range(1, n + 1))\n",
    "    index = 0  # 当前报数到的人的索引\n",
    "    \n",
    "    while len(people) > 1:\n",
    "        # 计算下一个要退出的人的索引（注意Python的索引是从0开始的，所以这里要加1再模长度）\n",
    "        index = (index + k - 1) % len(people)\n",
    "        # 移除该人\n",
    "        people.pop(index)\n",
    "    \n",
    "    # 返回最后留下的人的编号\n",
    "    return people[0]\n",
    " \n",
    "# 示例用法\n",
    "n = int(input(\"请输入总人数n: \"))\n",
    "k = 3  # 报数的间隔，题目中给出是3\n",
    "result = josephus(n, k)\n",
    "print(f\"最后留下的是原来第{result}号的那位。\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
